<template>
	<view class="container">
		<view class="container-header">
			<view class="header-content">
				<view class="back-button" @click="goBack()">
					<u-icon name="arrow-left" color="#000" size="20"></u-icon>
				</view>
				<view class="title">
					个人资料
				</view>
				<view class="back-button-right">
					常见问题
				</view>
			</view>
		</view>

		<u-line color="rgba(41, 41, 48, 0.05)"></u-line>

		<view class="content-header">
			<view class="content-header-imgBox">
				<view class="content-header-imgBox-left">
					<image src="/static/authentication/expertInformation-write.png" mode=""></image>
				</view>
				<view class="content-header-imgBox-right">
					请按要求填写以下信息，成功申请后将直接展示在您的达人主页中
				</view>
			</view>

			<view class="content-footer">
				<view class="content-footer-hr">
					<view class="content-footer-hr-header">
						<view class="content-footer-hr-header-h2">
							上传头像
						</view>
						<view class="content-footer-hr-header-h3">
							（上传本人真实照片，五官清晰）
						</view>
					</view>

					<view class="content-footer-hr-footer">
						<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
							:maxCount="1">
							<image src="/static/authentication/expertInformation-upLoadPicture.png" mode="widthFix"
								style="width: 144rpx;height: 144rpx;"></image>
						</u-upload>
					</view>
				</view>

				<view class="content-footer-hr">
					<view class="content-footer-hr-header">
						<view class="content-footer-hr-header-h2">
							个人介绍
						</view>
						<view class="content-footer-hr-header-h3">
							（为你的达人身份写一段自我介绍吧~）
						</view>
					</view>

					<view class="content-footer-hr-footer">
						<view class="My-textarea">
							<!-- <textarea :placeholderStyle="{fontSize: '26rpx'}" placeholder="占位符字体是红色的" /> -->
							<uni-easyinput type="textarea" v-model="queryParams.value1"
								placeholder="例：土生土长xx人，主打“不绕路、不踩坑”，平常热爱健身运动。家里有一只边牧，休息经常带狗子去附近自驾遛弯......能唠景点冷知识，还能带你钻老巷吃隐藏美食，连老板多给勺辣椒都能帮你搞定～"
								:inputBorder="false" maxlength="150"
								style="font-size: 26rpx;background-color:rgba(248, 248, 248, 1);"></uni-easyinput>
							<view class="inputCount">
								{{ queryParams.value1.length || 0 }}/150
							</view>
						</view>
					</view>
				</view>


				<view class="footer-btn-wrapper" @click="handleEmit()">
					<view class="footer-btn">
						保存
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import config from '@/config/index.js'
	import {
		expertAddOrEdit
	} from '@/request/api.js';
	export default {
		data() {
			return {
				fileList1: [],
				queryParams: {
					avatar: '', //上传的图片数组
					value1: ''
				},
				selected: false,

			};
		},
		onReady() {

		},
		onLoad(options) {
			if (options.expertInfo) {
				try {
					let expertInfo = JSON.parse(decodeURIComponent(options.expertInfo));
					console.log(expertInfo);
					this.queryParams.avatar = expertInfo.avatar
					this.queryParams.value1 = expertInfo.des ? expertInfo.des : ''
					// 正确的回显方式：构建完整的文件列表对象
					if (expertInfo.avatar) {
						this.fileList1 = [{
							url: expertInfo.avatar,
							status: 'success',
							message: ''
						}];
					}
				} catch (error) {
					console.error('解析专家信息失败:', error);
				}
			}
		},
		onReachBottom() {},

		methods: {
			handleEmit() {

				// 验证所有条件
				const validation = this.validateSubmission();
				if (!validation.isValid) {
					uni.showToast({
						title: validation.message,
						icon: 'none'
					});
					return;
				}

				let params = {
					userId: this.$store.state.userInfo.userId,
					des: this.queryParams.value1,
					avatar: this.queryParams.avatar,
					expertStarts: 3

				}
				expertAddOrEdit(params).then(res => {
					console.log(res.data.code == 200);
					if (res.data.code == 200) {
						uni.navigateBack()
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						});
					}
				})
			},
			// 验证提交条件
			validateSubmission() {
				if (!this.queryParams.avatar) {
					return {
						isValid: false,
						message: '请上传头像'
					};
				}
				if (!this.queryParams.value1) {
					return {
						isValid: false,
						message: '请填写个人资料'
					};
				}


				return {
					isValid: true,
					message: ''
				};
			},
			// 切换复选框状态
			toggleCheckbox() {
				this.selected = !this.selected;
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;

				// 先添加到文件列表，设置为上传中状态
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});

				for (let i = 0; i < lists.length; i++) {
					try {
						const result = await this.uploadFilePromise(lists[i].url);
						let item = this[`fileList${event.name}`][fileListLen];
						this[`fileList${event.name}`].splice(
							fileListLen,
							1,
							Object.assign(item, {
								status: "success",
								message: "",
								url: result,
							})
						);
					} catch (error) {
						// 上传失败时更新文件状态
						let item = this[`fileList${event.name}`][fileListLen];
						this[`fileList${event.name}`].splice(
							fileListLen,
							1,
						);
						// 同时显示错误提示
						uni.showToast({
							title: error.message || '上传失败',
							icon: 'none'
						});
					}
					fileListLen++;
				}
			},
			uploadFilePromise(url) {
				let _that = this
				const base_url = config.baseURL
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: base_url + '/qnyUpload/upload',
						filePath: url,
						name: "file",
						header: {
							'Authorization': uni.getStorageSync('token') || '',
							'Accept': 'application/json'
						},
						success: (res) => {
							console.log(res);
							// 检查HTTP状态码
							if (res.statusCode === 413) {
								reject(new Error('图片过大，请选择较小的图片'));
								return;
							}

							// 检查其他错误状态码
							if (res.statusCode !== 200) {
								reject(new Error(`上传失败，状态码：${res.statusCode}`));
								return;
							}

							try {
								// 解析服务器返回的数据
								const responseData = typeof res.data === 'string' ? JSON.parse(res
									.data) : res.data;

								// 检查响应状态
								if (responseData.code === 200) {
									// 成功获取网络地址
									const imageUrl = responseData.url;
									// 将图片URL添加到imageList数组中
									if (imageUrl) {
										this.queryParams.avatar = imageUrl;
									}
									resolve(imageUrl);
								} else {
									// 业务逻辑错误
									console.error('上传失败:', e);
									reject(new Error(responseData.msg || '上传失败'));
								}
							} catch (error) {
								// 解析失败
								console.error('响应数据解析失败:', error);
								reject(new Error('服务器响应格式错误'));
							}
						},
						fail: (err) => {
							// 网络请求失败
							// 根据错误类型提供更具体的错误信息
							if (err.errMsg && err.errMsg.includes('request:fail')) {
								reject(new Error('网络连接失败，请检查网络设置'));
							} else {
								reject(new Error('网络请求失败'));
							}
						}
					});
				});
			},
			// 删除图片
			deletePic(event) {
				this.queryParams.avatar = '';
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			goBack() {
				uni.navigateBack()
			},
			setStatusBarWhite() {
				// 设置状态栏前景色为白色
				uni.setNavigationBarColor({
					frontColor: '#ffffff',
					backgroundColor: '#000000',
					animation: {
						duration: 200,
						timingFunc: 'easeIn'
					}
				});
			},

			setStatusBarBlack() {
				// 如果需要切换回黑色
				uni.setNavigationBarColor({
					frontColor: '#000000',
					backgroundColor: '#ffffff',
					animation: {
						duration: 200,
						timingFunc: 'easeIn'
					}
				});
			},
		}
	};
</script>

<style lang="scss" scoped>
	page {
		background-color: #f8f8f8;
	}

	.container {
		height: 100%;

		.container-header {
			/* 增加顶部间距，提供更多与状态栏的距离 */
			height: calc(var(--status-bar-height) + 60rpx);
			display: flex;
			align-items: flex-end;
			/* 将内容对齐到底部 */
			padding-bottom: 30rpx;
			/* 底部留白 */

			.header-content {
				display: flex;
				justify-content: space-between;
				align-items: center;
				width: 100%;
				padding: 0 30rpx;
				position: relative;
				/* 添加相对定位 */

				.back-button {
					display: flex;
					align-items: center;
					justify-content: center;
					height: 40rpx;
					/* 确保左侧按钮不占用过多空间 */
					flex-shrink: 0;
				}

				.back-button-right {
					display: flex;
					align-items: center;
					justify-content: center;
					color: #000000;
					font-weight: 400;
					font-size: 24rpx;
					height: 40rpx;
					line-height: 40rpx;
					/* 确保右侧按钮不占用过多空间 */
					flex-shrink: 0;
				}

				.title {
					font-weight: bold;
					font-size: 30rpx;
					color: rgba(0, 0, 0, 0.9);
					/* 绝对定位使标题真正居中 */
					position: absolute;
					left: 50%;
					transform: translateX(-50%);
					/* 防止标题过长影响布局 */
					white-space: nowrap;
					/* 确保标题在其他元素之上 */
					z-index: 1;
				}
			}
		}

		.content-header {
			margin: 40rpx 30rpx;

			.content-header-imgBox {
				height: 208rpx;
				background: linear-gradient(to right, rgba(255, 186, 25, 1), rgba(255, 228, 49, 1));
				border-radius: 20rpx;
				display: flex;

				.content-header-imgBox-left {
					width: 180rpx;
					height: 180rpx;
					flex-shrink: 0;
					/* 防止收缩 */

					image {
						width: 100%;
						height: 100%;
					}
				}

				.content-header-imgBox-right {
					color: rgba(0, 0, 0, 1);
					font-size: 26rpx;
					font-weight: 400;
					margin: 34rpx 30rpx 34rpx 0;
					font-size: 26rpx;
					font-weight: 400;
					line-height: 40rpx;
				}
			}
		}

		.content-footer {
			margin-top: -60rpx;
			background-color: #fff;
			border-radius: 20rpx;
			height: 700rpx;
			position: relative;
			z-index: 1;

			.content-footer-hr {
				padding-top: 20rpx;

				.content-footer-hr-header {
					display: flex;
					padding: 20rpx 30rpx 0;
					align-items: baseline;

					.content-footer-hr-header-h2 {
						font-weight: bold;
						font-size: 30rpx;
						color: #000000;
						margin-right: 10rpx;
					}

					.content-footer-hr-header-h3 {
						font-weight: 400;
						font-size: 24rpx;
						color: rgba(77, 77, 86, 1);
					}
				}

				.content-footer-hr-footer {
					padding: 20rpx 30rpx 0;

					.My-textarea {
						background-color: rgba(248, 248, 248, 1);
						border-radius: 10rpx;
						padding: 10rpx;
						position: relative; // 添加相对定位

						.inputCount {
							position: absolute;
							bottom: 20rpx;
							right: 20rpx;
							font-size: 24rpx;
							color: #999;
							background-color: rgba(248, 248, 248, 0.8);
							padding: 4rpx 10rpx;
							border-radius: 6rpx;
						}
					}
				}
			}
		}


		/* 底部按钮固定容器 */
		.footer-btn-wrapper {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			display: flex;
			justify-content: center;
			padding: 20rpx 0 50rpx;
			background: linear-gradient(to bottom, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1));

			/* 渐变背景 */

			.footer-btn {
				background-color: rgba(255, 179, 39, 1);
				font-weight: 900;
				font-size: 36rpx;
				line-height: 36rpx;
				padding: 30rpx 36rpx;
				text-align: center;
				width: 570rpx;
				border-radius: 40rpx;
				color: rgba(0, 0, 0, 1);
				box-shadow: 0 8rpx 20rpx rgba(255, 179, 39, 0.3);
			}
		}
	}
</style>